//
//  AsyncURLconnection.m
//  MoreConnection
//
//  Created by dllo on 15/8/7.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "AsyncURLconnection.h"

@interface AsyncURLconnection ()<NSURLConnectionDataDelegate, NSURLConnectionDelegate>

@property (nonatomic, retain)NSMutableData *data;

@end
@implementation AsyncURLconnection
- (void)dealloc
{
    [_data release];
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.data = [NSMutableData data];
    }
    return self;
}
+ (instancetype)asyncURLconnectionWith:(NSString *)urlStr parmaters:(NSDictionary *)parmaters Delegate:(id<AsyncURLconnectionDelegate>)delegate
{
    
    // 添加post参数
    // 封装post参数

    NSData *data = [NSJSONSerialization dataWithJSONObject:parmaters options:NSJSONWritingPrettyPrinted error:nil];
//    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    
    
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:data];
    
    AsyncURLconnection *asy = [[AsyncURLconnection alloc]init ];
    asy.delegate = delegate;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
       
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
      
        [asy.delegate sendWithData:data];
        
        
    }];
    
//    [NSURLConnection connectionWithRequest:request delegate:asy];
    return [asy autorelease];

}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  

    [self.delegate sendWithData:self.data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    [self.data appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
}

@end
